package com.wwf;

import com.wwf.util.JSONSerializer;
import com.wwf.util.RpcDecode;
import com.wwf.util.RpcEncode;
import com.wwf.util.RpcRequest;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.context.ApplicationContext;

/**
 * @author lulei
 * @date 2021年01月08日 14:56:17
 */
public class StartServer {
    /**
     * 启动服务提供者
     * @param hostname 域名
     * @param port 端口号
     * @throws InterruptedException
     */
    public static  void startServer(String hostname, int port, final ApplicationContext applicationContext) throws InterruptedException {
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();
        io.netty.bootstrap.ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(bossGroup,workGroup)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel ch) throws Exception {
                        ChannelPipeline pipeline = ch.pipeline();
                        pipeline.addLast(new StringEncoder());
                        pipeline.addLast(new RpcDecode(RpcRequest.class, new JSONSerializer()));
                        pipeline.addLast(new UserServerHandler(applicationContext));
                    }
                });
        serverBootstrap.bind(hostname,port).sync();
    }
}
